# -*- coding: utf-8 -*-
from utils.config import *
from utils.utils import *
import pandas as pd
import utils.MyTT as Mytt
# import logging
from utils.log import Loggers
from utils.pushService import PushService

logger = Loggers('DonchianChannels')
# logger.clear()

pushSer = PushService('唐奇安通道逆势策略')

# 动态调整ATR倍数（根据市场波动率）
def dynamic_multiplier(atr_ratio):
    # atr_ratio = myAtr / YearAtr
    if atr_ratio > 1.5:  # 高波动期
        return 1.5  
    elif atr_ratio < 0.7: # 低波动期
        return 3
    else:
        return 2.5

# 计算止损点位，使用动态atr 进行止损计算
def getZhisun(after_signal):
        # 动态计算小数位
    xiaoshuwei = 1 if after_signal['close']>0 else 4
    atr_value = dynamic_multiplier(after_signal['atr40']/after_signal['atr130']) * after_signal['atr40']
    value = (   atr_value if after_signal['signal'] <0 else  atr_value*-1)
    return round(after_signal['close'] + value,xiaoshuwei), round(after_signal['close'] - value,xiaoshuwei)
    

# 循环处理
for instId in config_movingAverage_instId:
    # 读取300条最新的数据
    try:
        df = loadCsvData(instId,'4h')
    except:
        continue

    # 计算指标 唐奇安通道
    df['tqa_UP'],_,df['tqa_DOWN'] = Mytt.TAQ(df['high'],df['low'],130)
    
    # print(df.tail(30))
    # exit()

    df['atr40'] = Mytt.ATR(df['close'],df['high'],df['low'],40)
    df['atr130'] = Mytt.ATR(df['close'],df['high'],df['low'],130)
    

    # 寻找信号
    df['signal'] = 0
    df.loc[(df['atr40'] > df['atr130'] ) & (df['close'] > df['tqa_UP'].shift(1)),'signal'] = -1
    df.loc[(df['atr40'] > df['atr130'] ) & (df['close'] < df['tqa_DOWN'].shift(1)),'signal'] = 1

    # 快速计算信号近期胜率
    shenglv5,shenglv10 = getShenglv(df)

    # 取出所有满足条件的信号数据
    df_signal = df[df['signal']!=0]
    # getShenglvShow(df,instId)
    # exit()
    # 拿到最后出现信号的数据
    after_signal = df_signal.iloc[-1]
    # print(after_signal['tqa_UP'],after_signal['tqa_DOWN'])
    fangxiang = '做多' if after_signal['signal']>0 else '做空'
    signal_text = f"{instId}{fangxiang} 最近信号：{after_signal.name} 收盘价：{after_signal['close']} "

    # 计算止损位置
    # tqnWidth = (after_signal['tqa_UP'] - after_signal['tqa_DOWN']) * 1
    zhisun,zhiying = getZhisun(after_signal)
    # zhiying = round(after_signal['tqa_UP'] if after_signal['signal']>0 else after_signal['tqa_DOWN'],xiaoshuwei)
    # zhiyingR = round(abs((zhiying - after_signal['close']))/after_signal['close'] *100,2)

    # zhisun = round(after_signal['close'] + (tqnWidth if  after_signal['signal']<0 else (tqnWidth*-1)),xiaoshuwei)
    zhisunR = round( abs((zhisun - after_signal['close'])) /after_signal['close'] *100,2)

    signal_text+= f"止损：{zhisun}({zhisunR}%)"
    hour = getHoursPassed(after_signal.name)
    # logger.info(signal_text)
    # exit()
    # 进行日志记录
    if hour < 8:
        # 8小时内的新信号 就可以 进行钉钉推送
        if pushSer.add_push_item(after_signal, instId,[
            # f"止盈：{zhiying}({zhiyingR}%)",
            f"止损：{zhisun}({zhisunR}%)",
        ]):
            logger.info(signal_text)

    # 完成消息的通知
pushSer.push_message()

